<!-- filename: frontend/src/pages/notifications/notifications.vue -->
<template>
  <view class="page-container">
    <Header @open-auth-modal="isAuthModalVisible = true" />
    <AuthModal v-if="isAuthModalVisible" @close="isAuthModalVisible = false" />

    <view class="content-wrapper">
      <view class="page-header">
        <h1 class="page-title">我的通知</h1>
      </view>

      <!-- 标签页导航 -->
      <view class="tabs-container">
        <view 
          v-for="tab in tabs" 
          :key="tab.key" 
          class="tab-item" 
          :class="{ active: activeTab === tab.key }"
          @click="switchTab(tab.key)"
        >
          <text>{{ tab.name }}</text>
          <view v-if="unreadCounts[tab.countKey] > 0" class="tab-badge">
              {{ unreadCounts[tab.countKey] }}
          </view>
        </view>
      </view>

      <!-- 通知列表 -->
      <view class="notifications-list-wrapper">
        <!-- 【新增】分页控件 -->
        <ListControls
          v-if="!isLoading && notifications.length > 0"
          :pagination="pagination"
          context="comments"
          @update:page="handlePageChange"
        />

        <view v-if="isLoading" class="loading-state">正在加载...</view>
        <view v-else-if="notifications.length === 0" class="empty-state">
          这里空空如也～
        </view>
        <view v-else>
          <!-- 一键已读按钮 -->
          <view v-if="unreadCounts[activeTabCountKey] > 0" class="mark-all-read-btn" @click="markGroupAsRead">
            将本页全部标记为已读
          </view>
          
          <view class="notifications-list">
            <view 
              v-for="n in notifications" 
              :key="n.id" 
              class="notification-item" 
              :class="{ unread: !n.is_read }"
              @click="handleNotificationClick(n)"
            >
              <view class="avatar-wrapper">
                <image v-if="n.sender_avatar_url" :src="n.sender_avatar_url" class="avatar-image" mode="aspectFill"/>
                <!-- 系统通知使用特殊图标 -->
                <view v-else class="avatar-placeholder system-icon">
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="white"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/></svg>
                </view>
              </view>
              <view class="notification-main">
                <view class="notification-content" v-html="formatNotificationContent(n)"></view>
                <view class="timestamp">{{ n.created_at }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>


<script setup>
import { ref, computed } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { useAuthStore } from '@/store/auth';
import { useSearchStore } from '@/store/search';
import { request } from "@/utils/request"; // 【核心修改1】

import Header from '@/components/Header/Header.vue';
import AuthModal from '@/components/AuthModal/AuthModal.vue';
import ListControls from '@/components/ListControls/ListControls.vue';

const authStore = useAuthStore();
const searchStore = useSearchStore();
const isAuthModalVisible = ref(false);

const tabs = [
  { key: 'interactions', name: '评论和点赞', countKey: 'notifications_interactions' },
  { key: 'system', name: '系统通知', countKey: 'notifications_system' },
];

const activeTab = ref('interactions');
const notifications = ref([]);
const isLoading = ref(true);
const pagination = ref({ current_page: 1, total_pages: 1, total_items: 0 });

const unreadCounts = computed(() => authStore.unreadCounts || {});
const activeTabCountKey = computed(() => tabs.find(t => t.key === activeTab.value)?.countKey);

// --- 【核心修改2】重写所有 API 请求函数 ---

const fetchNotifications = async (page = 1) => {
  if (!authStore.isLoggedIn) {
    isLoading.value = false;
    notifications.value = [];
    return;
  }
  isLoading.value = true;
  if (page === 1) notifications.value = [];

  try {
    const data = await request({
      url: `/api/me/notifications?group=${activeTab.value}&page=${page}`,
      method: 'GET'
    });
    if (data && data.notifications) {
      notifications.value = data.notifications;
      pagination.value = data.pagination;
    } else {
      notifications.value = [];
    }
  } catch (error) {
    console.error("Failed to fetch notifications:", error);
    notifications.value = [];
  } finally {
    isLoading.value = false;
  }
};

const markNotificationsAsRead = (ids) => {
  return request({
    url: `/api/me/notifications/mark-as-read`,
    method: 'POST',
    data: { ids: ids },
  });
};

const markGroupAsRead = async () => {
    const groupKey = activeTab.value;
    uni.showLoading({ title: '正在处理...' });
    
    try {
        await request({
            url: `/api/me/notifications/mark-as-read`,
            method: 'POST',
            data: { group: groupKey },
        });
        fetchNotifications();
        authStore.fetchTotalUnreadCounts();
    } catch (error) {
        uni.showToast({ title: '操作失败', icon: 'none' });
    } finally {
        uni.hideLoading();
    }
};

const handleNotificationClick = async (n) => {
  if (!n.is_read) {
    markNotificationsAsRead([n.id]).then(() => {
      authStore.fetchTotalUnreadCounts();
    });
    n.is_read = true;
  }

  const sourceType = n.target_type;
  const sourceId = n.source_id;
  const commentId = n.target_id;
  const parentId = n.parent_id;

  const handleSongJump = async (openComment) => {
    if (sourceId) {
      uni.showLoading({ title: '正在定位歌曲...' });
      try {
        const jumpTaskData = await request({
          url: `/api/songs/location/${sourceId}`,
          method: 'GET'
        });
        searchStore.setPendingJump({
          page: jumpTaskData.page,
          sort_by: jumpTaskData.sort_by,
          highlight_song_id: sourceId,
          open_comment: openComment,
          highlight_comment_id: commentId,
          highlight_parent_id: parentId
        });
        uni.switchTab({ url: `/pages/index/index` });
      } catch (error) {
        uni.showToast({ title: '定位歌曲失败', icon: 'error' });
      } finally {
        uni.hideLoading();
      }
    }
  };

  switch (n.type) {
    case 'song_comment_reply':
    case 'song_comment_like':
    case 'song_new_comment':
    case 'song_new_reply':
      handleSongJump(true);
      break;

    case 'song_like':
    case 'song_approved':
      handleSongJump(false);
      break;

    case 'playlist_comment_reply':
    case 'playlist_comment_like':
    case 'playlist_new_comment':
    case 'playlist_collection':
      if (sourceId) {
        let url = `/pages/public-playlist-detail/public-playlist-detail?id=${sourceId}`;
        if (n.type !== 'playlist_collection') {
            url += `&action=find_comment&parent_id=${parentId || ''}&comment_id=${commentId}`;
        }
        uni.navigateTo({ url });
      }
      break;

    case 'song_rejected':
    default:
      break;
  }
};


// --- 无需修改的函数 ---
onShow(() => {
  if (authStore.isLoggedIn) {
    authStore.fetchTotalUnreadCounts();
    fetchNotifications(1);
  } else {
    isLoading.value = false;
    notifications.value = [];
  }
});

const switchTab = (tabKey) => {
  if (activeTab.value === tabKey) return;
  activeTab.value = tabKey;
  fetchNotifications(1);
};

const handlePageChange = (newPage) => {
  fetchNotifications(newPage);
};

const formatNotificationContent = (n) => {
  const sender = `<b>${n.sender_username || '系统'}</b>`;
  const sourceName = n.source_song_title || n.source_playlist_name;
  const sourceHtml = sourceName ? `在歌曲 <span>《${sourceName}》</span>` : '';
  const playlistHtml = sourceName ? `在你的歌单 <span>《${sourceName}》</span>` : '';

  switch (n.type) {
    case 'song_comment_reply':
      return `${sender} ${sourceHtml} 回复了你的评论`;
    case 'playlist_comment_reply':
      return `${sender} ${playlistHtml} 回复了你的评论`;
    case 'song_comment_like':
      return `${sender} 点赞了你 ${sourceHtml} 中的评论`;
    case 'playlist_comment_like':
      return `${sender} 点赞了你 ${playlistHtml} 中的评论`;
    case 'playlist_new_comment':
      return `${sender} 评论了你的歌单 <span>《${sourceName || ''}》</span>`;
    case 'playlist_collection':
      return `${sender} 收藏了你的歌单 <span>《${sourceName || ''}》</span>`;
    case 'song_like':
      return `${sender} 点赞了你上传的歌曲 <span>《${sourceName || ''}》</span>`;
    case 'song_new_comment':
      return `${sender} 评论了你上传的歌曲 <span>《${sourceName || ''}》</span>`;
    case 'song_new_reply':
      return `${sender} 在你上传的歌曲 <span>《${sourceName || ''}》</span> 下发表了新回复`;
    case 'song_approved':
    case 'song_rejected':
      return n.content; 
    default:
      return `未知类型的通知`;
  }
};

</script>

<style scoped lang="scss">
.page-container { background-color: #f8f8f8; min-height: 100vh; }
.content-wrapper { padding-top: 60px; max-width: 800px; margin: 0 auto; }
.page-header { padding: 20px; }
.page-title { font-size: 24px; font-weight: bold; }
.loading-state, .empty-state { text-align: center; padding: 80px 20px; color: #888; }

/* Tabs */
.tabs-container { display: flex; background-color: #fff; border-bottom: 1px solid #f0f0f0; padding: 0 10px; }
.tab-item {
  position: relative;
  padding: 15px;
  margin: 0 10px;
  font-size: 16px;
  color: #666;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  &.active { font-weight: bold; color: #007aff; border-bottom-color: #007aff; }
}
.tab-badge {
  position: absolute;
  top: 10px;
  right: -5px;
  background-color: #e5245e;
  color: white;
  min-width: 18px;
  height: 18px;
  border-radius: 9px;
  font-size: 11px;
  display: flex; align-items: center; justify-content: center;
  padding: 0 5px;
}

/* List */
.notifications-list-wrapper { background-color: #fff; }
.mark-all-read-btn {
    padding: 10px 20px;
    text-align: right;
    font-size: 13px;
    color: #007aff;
    cursor: pointer;
    border-bottom: 1px solid #f0f0f0;
}
.notification-item {
  display: flex;
  gap: 15px;
  padding: 15px 20px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  &:hover { background-color: #f9f9f9; }
  &.unread { background-color: #f0f8ff; }
}
.avatar-wrapper { flex-shrink: 0; }
.avatar-image { width: 45px; height: 45px; border-radius: 50%; }
.avatar-placeholder {
  width: 45px; height: 45px; border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  &.system-icon { background-color: #007aff; }
}
.notification-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 5px;
}
.notification-content {
  font-size: 15px;
  line-height: 1.5;
  // 使用 :deep() 来穿透 v-html 的样式
  :deep(b) { font-weight: 500; }
  :deep(span) { color: #007aff; }
}
.timestamp { font-size: 12px; color: #aaa; }
</style>